import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HEROES } from '../mock-heroes';
import { HeroService } from '../hero.service';

@Component({
  // CSS 元素选择器. app-heroes 用来在父组件的模板中匹配 HTML 元素的名称，以识别出该组件
  // 没有子组件的导入,注册过程.只有声明过程
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {

  heroes: Hero[] = HEROES

  // 注入HeroService
  constructor(private heroService: HeroService) { }
  // 生命周期钩子,创建完组件后很快就会调用
  ngOnInit() {
    this.getHeroes();
  }
  getHeroes(): void {
    // HttpClient.get  请求服务
    // Observable类通过.subscribe()消费数据(与Promise,then类似)
    this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes.slice(1, 5));
  }
  add(name: string): void {
    name = name.trim();
    if (!name) { return; }
    this.heroService.addHero({ name } as Hero)
      .subscribe(hero => {
        this.heroes.push(hero);
      });
  }
  delete(hero: Hero): void {
    this.heroes = this.heroes.filter(h => h !== hero);
    this.heroService.deleteHero(hero).subscribe();
  }
}